package com.example.com.daervideo.activitys.users;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDialog;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.com.daervideo.R;
import com.example.com.daervideo.databinding.ActivityUserBinding;
import com.example.com.daervideo.entity.UserData;
import com.example.com.daervideo.initerface.ApiService;
import com.example.com.daervideo.initerface.NetCallback;
import com.example.com.daervideo.popuwindow.SignNamePpwindow;
import com.example.com.daervideo.utils.ImageSelectTool;
import com.example.com.daervideo.utils.RetrofitClient;
import com.example.com.daervideo.BR;

import java.io.File;
import java.io.Serializable;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.BaseUrlExternalStrageDir;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.MaterialDialogUtils;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Created by i7-1 on 2018/12/6.
 */

public class UserInfoActivity extends BaseActivity<ActivityUserBinding, UserData> implements View.OnClickListener {

    private ImageSelectTool imageSelectTool;
    private MaterialDialog.Builder signNameBuilding;
    private MaterialDialog.Builder nikeNameBuilding;
    private ApiService apiService;
    private UserData userdata;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initData();
    }

    @Override
    public int initContentView() {
        return R.layout.activity_user;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public UserData initViewModel() {
        return new UserData();
    }

    @Override
    public void initParam() {
        super.initParam();
        Bundle extras = getIntent().getBundleExtra("bundle");

        if (extras != null) {
            userdata = (UserData) extras.getSerializable("entity");
        }
    }

    @Override
    public void initData() {

        getBinding().setM(userdata);

        apiService = RetrofitClient.getInstance().create(ApiService.class);

        ImageView imageView = (ImageView) findViewById(R.id.icon);
        imageView.setOnClickListener(this);

        int width = 80;
        int height = 80;

        String path = BaseUrlExternalStrageDir.getBaseUrl() + "/user" + "temp.png";
        imageSelectTool = new ImageSelectTool(width, height, this, path, new NetCallback() {
            @Override
            public void callback(final String url) {
                File file = new File(url);
            }
        });

        nikeNameBuilding = MaterialDialogUtils.showInputDialog(this, "编辑昵称", "昵称", new MaterialDialog.InputCallback() {
            @Override
            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                editNickName(input);
            }
        });

        signNameBuilding = MaterialDialogUtils.showInputDialog(this, "编辑个人签名", "签名", new MaterialDialog.InputCallback() {
            @Override
            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                editSign(input);
            }
        });

        findViewById(R.id.edit_nike_name).setOnClickListener(this);
        findViewById(R.id.edit_sign).setOnClickListener(this);

    }


    private void _checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)//相机
                    != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)   //可读
                            != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)  //可写
                            != PackageManager.PERMISSION_GRANTED) {

                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                showIconDialog();
            }
        } else {
            showIconDialog();
        }
    }

    private void showIconDialog() {
        //成功时会返回相应的文件地址"/iden" + index + "temp.jpg"
        String path = BaseUrlExternalStrageDir.getBaseUrl() + "/user" + "temp.png";
        imageSelectTool.filePath = path;
        imageSelectTool.menuWindow.showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imageSelectTool.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (1 == requestCode) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)//相机
                    == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)   //可读
                            == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)  //可写
                            == PackageManager.PERMISSION_GRANTED) {
            } else {
                showIconDialog();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_sign:
                signNameBuilding.show();
                break;
            case R.id.edit_nike_name:
                nikeNameBuilding.show();
                break;
            case R.id.icon:
                _checkPermission();
                break;
        }
    }


    private void editNickName(CharSequence input) {
        final String name = input.toString().trim();
        if (name.length() == 0)
            return;
        apiService.editName(name, null) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse response) throws Exception {
                        ToastUtils.showShort(response.getMsg());

                        getBinding().getM().setLoginName(name);

                    }
                }, new Consumer<ResponseThrowable>() {
                    @Override
                    public void accept(ResponseThrowable throwable) throws Exception {
                        ToastUtils.showShort(throwable.message);
                        throwable.printStackTrace();
                    }
                });

    }

    private void editSign(CharSequence input) {
        final String sign = input.toString().trim();
        if (sign.length() == 0)
            return;
        apiService.editSign(sign, "") //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse response) throws Exception {
                        getBinding().getM().setSign(sign);
                        ToastUtils.showShort(response.getMsg());
                    }
                }, new Consumer<ResponseThrowable>() {
                    @Override
                    public void accept(ResponseThrowable throwable) throws Exception {
                        ToastUtils.showShort(throwable.message);
                        throwable.printStackTrace();
                    }
                });
    }
}
